package com.ck.framework.interceptor;

import com.ck.common.utils.id.IdUtils;
import com.ck.common.utils.txt.StringUtils;
import org.slf4j.MDC;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * @author ck
 * @date 2024/4/15 10:35
 * desc: 日志链路追踪拦截器
 * MDC(Mapped Diagnostic Context)诊断上下文映射，是@Slf4j提供的一个支持动态打印日志信息的工具。
 */

@Component
public class LogInterceptor implements HandlerInterceptor {

    private static final String MDC_TRACE_ID="trace_id";

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        String traceId=request.getHeader(MDC_TRACE_ID);

        if (StringUtils.isEmpty(traceId)){
            traceId = IdUtils.fastUUID();
        }
        MDC.put(MDC_TRACE_ID,traceId);
        return true;
    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        MDC.remove(MDC_TRACE_ID);
    }
}
